﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using com.nm.ApiServer;
using System.ComponentModel;
using com.nm.ApiServer.Attributes;
using george.Data;
using com.nm.Attributes;
using com.nm.db.Models.Hkerp;
using CsrdAPI.model;
using EntityFramework.Extensions;
using george.Helper;
using System.Data;
using System.Collections;
using com.nm.library.Helper;
using CsrdAPI.Csrd;

namespace CsrdAPI
{
    [Description("销售查询")]
    public class SaleQueryHandler : BaseHandler
    {
        #region 销售查询
        [MustLogin]
        [JsonType]
        [Description("销售查询")]
        [ReturnType(typeof(PaperData<ListData>))]
        public ApiResult CrsdPosSale([ParamDescription("查询条件")] SearchData param)
        {
            if (param == null) return Error("参数对象为空！");
            if (string.IsNullOrWhiteSpace(param.CompanyID)) return Error("品牌不能为空！");
            if (string.IsNullOrWhiteSpace(param.SaleBeginDate) && string.IsNullOrWhiteSpace(param.BalanceDate)) return Error("销售开始日期不能空！");
            if (string.IsNullOrWhiteSpace(param.SaleEndDate) && string.IsNullOrWhiteSpace(param.BalanceDate)) return Error("销售结束日期不能空！");

            var dc = new CsrdEntities();
            var ShopList = "";
            var shopData = (from c in dc.Csrd_Client select c);

            //店铺
            if (!string.IsNullOrWhiteSpace(param.ShopStr))
            {
                shopData = shopData.Where(t => t.ShopName.Contains(param.ShopStr));
            }
            //合同日期
            if (!string.IsNullOrWhiteSpace(param.HtBeginDate) && !string.IsNullOrWhiteSpace(param.HtEndDate))
            {
                var bDate = Convert.ToDateTime(param.HtBeginDate);
                var eDate = Convert.ToDateTime(param.HtEndDate);
                shopData = shopData.Where(t => t.ContractBeginDate >= bDate && t.ContractEndDate <= eDate);
            }
            //会计期间
            if(param.DateType == 1)
            {
                param.SaleBeginDate = param.BalanceDate + "-01";
                param.SaleEndDate = Convert.ToDateTime(param.BalanceDate + "-01").AddMonths(1).AddDays(-1).ToString();
            }
            foreach (var item in shopData.ToList())
            {
                ShopList += item.ShopID + ",";
            }
            ShopList = ShopList.TrimEnd(',');

            var hk = new HKERPEntities();
            var query = hk.Database.SqlQuery<ListData>($@"exec KM_spSD_Rpt_CrsdPosSale '{param.CompanyID}','','{param.SaleBeginDate}','{param.SaleEndDate}','','{ShopList}',''").ToList();

            var result = PaperData<ListData>.Create(query.Count(), param.Size, param.Page);
            result.Items = query.OrderByDescending(t => t.Billdate)
                .Skip(result.Skip)
                .Take(result.Limt).ToList();
            return Success(result);
        }
        #endregion


        public class SearchData
        {
            [ParamDescription("页码")]
            public int Page { get; set; } = 1;
            [ParamDescription("页数")]
            public int Size { get; set; } = 10;
            [ParamDescription("合同开始日期")]
            public string HtBeginDate { get; set;}
            [ParamDescription("合同结束日期")]
            public string HtEndDate { get; set;}
            [ParamDescription("店铺")]
            public string ShopStr { get; set; }
            [ParamDescription("品牌")]
            public string CompanyID { get; set; }
            [ParamDescription("销售开始日期")]
            public string SaleBeginDate { get; set; }
            [ParamDescription("销售结束日期")]
            public string SaleEndDate { get; set; }
            [ParamDescription("会计期间")]
            public string BalanceDate { get; set; }
            [ParamDescription("时间类型")]
            public int DateType { get; set; }
        }

        private class ListData
        {
            [ParamDescription("品牌")]
            public string CompanyID { get; set; }
            [ParamDescription("销售日期")]
            public string Billdate { get; set; }
            [ParamDescription("店铺名称")]
            public string ShopName { get; set; }
            [ParamDescription("店铺代码")]
            public string ShopCode { get; set; }
            [ParamDescription("类别")]
            public string KindName { get; set; }
            [ParamDescription("系列")]
            public string SeriesName { get; set; }
            [ParamDescription("款号")]
            public string MaterialID { get; set; }
            [ParamDescription("数量")]
            public decimal Qty { get; set; }
            [ParamDescription("单价")]
            public decimal RetailPrice { get; set; }
            [ParamDescription("明细让利")]
            public decimal PresendAmount { get; set; }
            [ParamDescription("业绩金额")]
            public decimal Amount2 { get; set; }
            [ParamDescription("结算金额")]
            public decimal Amount { get; set; }
            [ParamDescription("礼券让利分摊")]
            public decimal THQPresend { get; set; }
            [ParamDescription("一般让利")]
            public decimal NormalPresend { get; set; }
            [ParamDescription("会员让利")]
            public decimal VipPresend { get; set; }
            [ParamDescription("储值卡让利分摊")]
            public decimal ValueCardPresend { get; set; }
            [ParamDescription("赠送分摊")]
            public decimal MasterPresend { get; set; }
            [ParamDescription("四舍五入让利分摊")]
            public decimal RoundAmount { get; set; }
            [ParamDescription("零售金额")]
            public decimal RetailAmount { get; set; }
            [ParamDescription("其他收入分摊")]
            public decimal OtherAmount { get; set; }
            [ParamDescription("会员红利")]
            public decimal Bonus { get; set; }
            [ParamDescription("其他收入让利分摊")]
            public decimal OtherPresend { get; set; }
            [ParamDescription("实际结算金额")]
            public decimal RealAmount { get; set; }
            [ParamDescription("积分抵现")]
            public decimal DischargeIntegralAmount { get; set; }
            [ParamDescription("会员优惠券分摊")]
            public decimal VIPCouponAmount { get; set; }
            [ParamDescription("商场对账扣减优惠券金额")]                         
            public decimal DecTHQMarkBalanceAmount { get; set; }
        }

        public DataTable ExportSaleQuery(string keys)
        {
            string wherekeys = keys.Replace(" ","").Replace("'","");
            string[] sArray = wherekeys.Split('*');
            //去除字符串数组里的空值
            sArray = sArray.Where(s => !string.IsNullOrEmpty(s)).ToArray();
            Dictionary<string, string> Dic = new Dictionary<string, string>();
            foreach (var item in sArray)
            {
                Dic.Add(item.Substring(0, item.IndexOf("=")), item.Substring(item.IndexOf('=') + 1));
            }
            string ShopStr = Dic.ContainsKey("shopStr") ? Dic["shopStr"] : "";
            string HtBeginDate = Dic.ContainsKey("ht_Begin") ? Dic["ht_Begin"] : "";
            string HtEndDate= Dic.ContainsKey("ht_End") ? Dic["ht_End"] : "";
            string SaleBeginDate = Dic.ContainsKey("sale_Begin") ? Dic["sale_Begin"] : "";
            string SaleEndDate = Dic.ContainsKey("sale_End") ? Dic["sale_End"] : "";
            string CompanyID = Dic.ContainsKey("company") ? Dic["company"] : "";
            string BalanceDate = Dic.ContainsKey("balanceDate") ? Dic["balanceDate"] : "";
            
            var dc = new CsrdEntities();
            var ShopList = "";
            var shopData = (from c in dc.Csrd_Client select c);

            //店铺
            if (!string.IsNullOrWhiteSpace(ShopStr))
            {
                shopData = shopData.Where(t => t.ShopName.Contains(ShopStr));
            }
            //合同日期
            if (!string.IsNullOrWhiteSpace(HtBeginDate) && !string.IsNullOrWhiteSpace(HtEndDate))
            {
                var bDate = Convert.ToDateTime(HtBeginDate);
                var eDate = Convert.ToDateTime(HtEndDate);
                shopData = shopData.Where(t => t.ContractBeginDate >= bDate && t.ContractEndDate <= eDate);
            }
            //会计期间
            if (!string.IsNullOrEmpty(BalanceDate))
            {
                SaleBeginDate = BalanceDate + "-01";
                SaleEndDate = Convert.ToDateTime(BalanceDate + "-01").AddMonths(1).AddDays(-1).ToString();
            }
            foreach (var item in shopData.ToList())
            {
                ShopList += item.ShopID + ",";
            }
            ShopList = ShopList.TrimEnd(',');
            var hk = new HKERPEntities();
            var query = hk.Database.SqlQuery<ListData>($@"exec KM_spSD_Rpt_CrsdPosSale '{CompanyID}','','{SaleBeginDate}','{SaleEndDate}','','{ShopList}',''").ToList();
            return DataTableHelper.LinqToDataTable(query);            
        }
    }
}
